import React, { Component } from 'react';
import Header from '../../components/Header';
import {connect} from 'react-redux';
import * as action from '../../redux/actions/home'
import Swiper from '../../components/Swiper/index'
import ScrollList from '../../components/ScrollList/index'
import './index.less'
import until from '../../common/until';
import {Link} from 'react-router-dom'
//{setCurrentLesson:function}
class Home extends Component {
    state = {  }
    chooseLesson=(type)=>{
        // console.log(state=>({...state}))
        // console.log(action)
        this.props.setCurrentLesson(type);
        // console.log( this.props.setCurrentLesson(type))
        this.props.getLesson()
    }
    componentDidMount(){
        //判断redux中是否存放了数据，如果有则不去获取数据
        if(this.props.home.lesson.lessonList.length === 0){
            this.props.getSlider(); //在页面调这个方法，就会取数据发给reducer，再放到redux
            this.props.getLesson(); //_store.getState
        }
        //让所有组件强制更新
        if(this.props.home.lesson.lessonList.length > 0){
            //将记录好的滚动条状态取出来付给content元素
            this.refs.scroll.scrollTop = until.get('homeLocation')
            this.forceUpdate()
        }
    }
    componentWillUnmount(){ //组件将要销毁的时候 记录滚动条的位置
        until.set('homeLocation',this.refs.scroll.scrollTop)
    }
    loadMore=()=>{
        this.props.getLesson();
    }
    render() { 
        let {hasMore,isLoading,lessonList} = this.props.home.lesson
        return ( 
            <div>
            <Header chooseLesson={this.chooseLesson}/>    
            {/* {this.props.home.currentLesson} */}
            <div className="content" ref="scroll">
                <ScrollList element={this.refs.scroll}
                    isLoading = {isLoading}
                    hasMore = {hasMore}
                    loadMore={this.loadMore}
                >
                    <Swiper data={this.props.home.sliders}/>
                    {/* 课程列表 */}
                    <div className="lesson-list">
                        { lessonList.length? lessonList.map((item,index)=>(
                            <Link to={{pathname:'/detail',state:item}} key={index} >
                                <div className="lesson">
                                    <img src={item.url} alt=""/>
                                    <p>{item.lesson}</p>
                                    <p>{item.price}</p>
                                </div> 
                            </Link>
                        )):<div>正在加载</div>}
                        <button className="load-more" onClick={this.loadMore}>点击加载</button>
                    </div>
                </ScrollList>
            </div>
            </div>
         );
    }
}
//mapStateToProps 将redux中的数据变成属性
//mapDispatchToProps 可以直接传一个actionCreator的对象
export default connect(state=>({...state}),action)(Home);
//{...state}相当于{currentLesson:state.home.currentLesson}